package com.uusee.crawler.pageprocessor.baike.imdb;

import com.uusee.crawler.framework.Processor;
import com.uusee.crawler.model.CrawlStatusCodes;
import com.uusee.crawler.model.CrawlURI;
import com.uusee.crawler.util.PageProcessorUtils;
import com.uusee.shipshape.bk.vo.Poster;
import com.uusee.util.StringUtils;

public class ImdbPosterPageProcessor extends Processor {
	private final String POSTER_ID_REG = "http://posters\\.imdb\\.cn/poster/([0-9]+)";
	private final String POSTER_REG = "<img src=\"(http://posters\\.imdb\\.cn/poster-pic/([0-9]+)/[^<]*?\\.jpg)\" alt=\"([^<]*?)海报\" border=8>";
	
	protected void innerProcess(CrawlURI crawlUri) {
		if (!canProcess(crawlUri)) {
			return;
		}
		
		try {
			String sourceSite = crawlUri.getSourceSite();
			String crawlUrl = crawlUri.getCrawlUrl();
			String crawlResult = crawlUri.getCrawlResult();
			String oriId = PageProcessorUtils.getValue(POSTER_REG, crawlResult, 2);
			String name = PageProcessorUtils.getValue(POSTER_REG, crawlResult, 3);
			String url = PageProcessorUtils.getValue(POSTER_REG, crawlResult, 1);
			String id = PageProcessorUtils.getValue(POSTER_ID_REG, crawlUrl, 1);
			
			if (StringUtils.isEmpty(url)) {
				crawlUri.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
				return;
			}
			
			Poster p = new Poster();
			p.setSourceSite(sourceSite);
			p.setOriId(oriId);
			p.setName(name);
			p.setUrl(url);
			p.setId(id);
			
			crawlUri.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_SUCCESS);
			crawlUri.setModel(p);
			
		} catch (Exception e) {
			crawlUri.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_EXCEPTION);
		}
		
	}
	
	private boolean canProcess(CrawlURI crawlURI) {
		int crawlStatus = crawlURI.getCrawlStatus();
		if (crawlStatus == CrawlStatusCodes.FETCH_SUCCESS) {
			return true;
		} else if (crawlStatus == CrawlStatusCodes.FETCH_SC_NOT_OK) {
			crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
			return false;
		} else {
			return false;
		}
	}

}
